const {db, Op} = require("../models/db");
const router = require('koa-router')();
const tool = require("../tools/tool");
const getOptionsByName = async (tenantId, name) => {
    return await db.models['options'].findOne({
        where: {
            tenantId,
            name
        }
    })
}
const printInfo = async ( vInvoice, tenantName, descript) => {
    try {
        let print_at = tool.getDay('',0,'DAY', 'YYYY/MM/DD')
        let print_at1 = tool.getDay('',0,'DAY', 'HH:mm')
        let customerName = vInvoice.buName
        let customerPhone = vInvoice.linkMobile
        let customerAddress = vInvoice.address
        let transType = tool.xe.toNumber(vInvoice.transType)
        let amount = 0
        let disAmount = tool.xe.toNumber(vInvoice.disAmount)
        let ysAmount = tool.xe.toNumber(vInvoice.ysAmount)
        let rpAmount = tool.xe.toNumber(vInvoice.rpAmount)
        let arrears = tool.xe.toNumber(vInvoice.arrears)
        let printNo = parseInt(vInvoice.printNo) + 1;
        let typename = vInvoice.transTypeName;
        let totalAmount = tool.xe.toNumber(vInvoice.totalAmount)
        let doName = vInvoice.doName?vInvoice.doName:''
        let userName = vInvoice.cbyName
        let salesName = vInvoice.salesName ?vInvoice.salesName:''
        let deliverNames = vInvoice.deliverNames?vInvoice.deliverNames:''
        if (vInvoice.billState === 'wasted') typename = typename + " - 退审票";
        if (vInvoice.billState === 'del') typename = typename + " - 已删票";
        let st = `<table cellpadding='0' cellspacing='0' style='border-collapse: collapse;width: 100%;' >
                            <thead> 
                            <tr>
                                <td style="text-align: center; height: 40px;" colspan='8'>
                                    <div style="text-align: center;">
                                        <div style='font-size: 22px'>${tenantName}</div>
                                        <div style='font-size: 18px'>（${typename}）</div>
                                        
                                    </div>
                                    <div style='position: absolute;left: 2px;top:10px;font-size: 13px;font-weight: normal'>
                                        <div style='text-align:left'>日期：${vInvoice.billDate}</div>
                                        <div style='text-align:left'>票号：${vInvoice.billNo}</div>
                                        
                                    </div>
                                    <div style='position: absolute;right: 0;top:1px;font-size: 12px;font-weight: normal'>
                                        <div><span tdata='PageNO'>##</span><span>/</span><span tdata='PageCount'>##</span>页</div> 
                                        <div><span></span> ${print_at}</div>
                                        <div><span></span> ${print_at1}-<span>${printNo}</span></div>
                                    </div>
                                </td>
                            </tr>
                      `
        switch (transType) {
            case 150501:
            case 150502:
            case 150706:{
                st += `<tr><td colspan='7' style='font-size: 14px'><div >客户：${customerName}</div></td></tr>
                        <tr>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>商品名称</td>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 75px;text-align: center;padding: 2px;'>辅助</td>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: center;padding: 2px;'>单位</td>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: center;padding: 2px;'>数量</td>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: center;padding: 2px;'>单价</td>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 70px;text-align: center;padding: 2px;'>金额</td>
                            <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                        </tr>
                    </thead>
                <tbody >
                `
                let list = await db.models['invoiceInfo'].findAll({
                    where: {
                        iid: vInvoice.id
                    }
                })
                for (let i = 0; i < list.length; i++) {
                    let it = list[i]
                    if (!it.invId) continue
                    it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                    it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                    st += `<tr>
                           <td style='border: 1px solid black;padding: 2px;text-align: left;'>${it.invName}</td>
                           <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.assQty}</td>
                           <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.unit}</td>
                           <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.qty ? it.qty : ''}</td>
                           <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.price}</td>
                           <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.amount}</td>
                           <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.remark ? it.remark : ''}</td>
                       </tr>`
                }
                // 如有收付款 再加一行
                if (rpAmount !== 0) {
                    st += `<tr>
                            <td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>已付：-</td>
                            <td style='border: 1px solid black;padding: 2px;text-align: right;'> ${rpAmount}</td><td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                           </tr>`
                }
                // 如有预收金额 再加一行
                if (ysAmount !== 0) {
                    st += `<tr><td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>预付：</td>
                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${-ysAmount}</td><td style='border: 1px solid black;padding: 2px;text-align: center;'></td></tr>`
                }
                // 应收 应付
                if (arrears !== 0) {
                    let s = "应付：";
                    st += `<tr><td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>${s}</td>
                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${arrears}</td><td style='border: 1px solid black;padding: 2px;text-align: center;'></td></tr>`
                }
                let c = tool.minus(totalAmount, rpAmount, ysAmount)
                if (c !== arrears) {
                    throw Error('票据金额不等于应收/付金额')
                }
                st += `</tbody><tfoot  >
                <tr><td colspan='7' style='border: 1px solid black;font-size: 14px;padding: 5px 0'><span>金额${arrears}</span>&nbsp;&nbsp;大写<span format='UpperMoney' tdata='${arrears}'>#</span></td></tr>
                <tr><td colspan='7' style='font-size: 14px'> <span>制单人:${userName}</span><span style='margin-left: 50px'>收货人:${deliverNames}</span></td></tr>
                </tfoot>`
            }
                break;
            case 150601:
            case 150602:
            case 150603:
            case 150806: {
                st += `<tr><td colspan='8' style='font-size: 14px'>`
                st += `<div ><span>客户：${customerName}</span></div>`
                st += `<div ><span >电话：${customerPhone}</span><span style='margin-left: 10px;'>地址：${customerAddress}</span></div>`
                st += `</td></tr>`
                if(transType === 150601) {
                    st += `
                         <tr>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;word-break:break-all;text-align: center;padding: 2px;'>商品名称</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 75px;text-align: center;padding: 2px;'>辅助</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: center;padding: 2px;'>单位</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: center;padding: 2px;'>数量</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: center;padding: 2px;'>单价</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: center;padding: 2px;'>返利</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 70px;text-align: center;padding: 2px;'>金额</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 70px;word-break:break-all;text-align: center;padding: 2px;'>备注</td>
                         </tr>
                     </thead>
                 <tbody>`
                    let list = await db.models['invoiceInfo'].findAll({
                        where: {
                            iid: vInvoice.id
                        }
                    })

                    let fl = 0
                    let allQty = 0
                    for (let i = 0; i < list.length; i++) {
                        let it = list[i]
                        if (!it.invId) continue;
                        it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                        it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                        let dedu = tool.xe.toNumber(it.deduction)
                        fl = tool.xe.add(fl, tool.xe.multiply(it.qty, dedu))
                        amount = tool.xe.add(amount, it.amount)
                        let send = it.send
                        let remark = it.remark
                        let mark = send + remark
                        allQty = tool.add(allQty, it.qty)
                        st += ` <tr>
                                    <td style='border: 1px solid black;padding: 2px; text-align: left;'>${it.invName}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.assQty}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.unit}</td>
                                    <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.qty}</td>
                                    <td style='border: 1px solid black;text-align: right;padding: 2px'>${tool.xe.toNumber(it.price)?it.price: ''}</td>
                                    <td style='border: 1px solid black;text-align: right;padding: 2px'>${tool.xe.toNumber(it.deduction)?it.deduction:''}</td>
                                    <td style='border: 1px solid black;text-align: right;padding: 2px'>${tool.xe.toNumber(it.amount)?it.amount:''}</td>
                                    <td style='border: 1px solid black;padding: 2px;font-size: 12px;text-align:left;'>${mark}</td>
                                </tr>`
                    }
                    // 如有优惠金额 再加一行
                    if (disAmount !== 0) {
                        st += `<tr>
                                    <td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td  style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td colspan='2' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>优惠金额：-</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${disAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    // 如有预收金额 再加一行
                    if (ysAmount !== 0) {
                        st += `<tr>
                                    <td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td  style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td colspan='2' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>预收：</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${-ysAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    // 如有收款金额 再加一行
                    if (rpAmount !== 0) {
                        st += `<tr>
                                    <td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td  style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td colspan='2' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>已收：-</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${rpAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    // 最后合计应收
                    if (arrears !== 0) {
                        st += `<tr>
                                    <td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td  style='border: 1px solid black;padding: 2px;text-align: right;'>${allQty}</td>
                                    <td colspan='2' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>应收合计：</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${vInvoice.arrears}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    st += `</tbody>
                                <tfoot >
                                <tr>
                                    <td colspan='8' style='border: 1px solid black;padding: 5px 0;font-size: 13px'><span>金额：${arrears} </span>大写：<span format='UpperMoney' tdata='${arrears}'>#</span></td> 
                                </tr>`
                    if(descript) {
                        st += ` <tr><td colspan='8' style=' padding-top: 2px;font-size: 12px;'>${descript}</td></tr>`
                    }
                    st += `<tr>
                                <td colspan='8' style='font-size: 14px'>
                                    <table style='width: 100%'>
                                        <tr>
                                            <td style='width: 120px;'>送货:</td>
                                            <td >制单:${userName}</td>
                                            <td >业务:${salesName}</td>
                                            <td style='width: 180px;'>未付款签字：</td>
                                        </tr>
                                    </table>
                                </td>
                           </tr>
                         </tfoot>`
                }
                if(transType === 150602) {
                    st += `<tr>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>商品名称</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 75px;text-align: center;padding: 2px;'>辅助</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: center;padding: 2px;'>单位</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: center;padding: 2px;'>数量</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: center;padding: 2px;'>单价</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 70px;text-align: center;padding: 2px;'>金额</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                             </tr>
                          </thead>
                        <tbody>`
                    let list = await db.models['invoiceInfo'].findAll({
                        where: {
                            iid: vInvoice.id
                        }
                    })
                    let fl = 0
                    let allQty = 0
                    for (let i = 0; i < list.length; i++) {
                        let it = list[i]
                        it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                        it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                        if (!it.invId) continue;
                        it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                        it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                        let dedu = tool.xe.toNumber(it.deduction)
                        fl = tool.xe.add(fl, tool.xe.multiply(it.qty, dedu))
                        amount = tool.xe.add(amount, it.amount)
                        allQty = tool.add(allQty, it.qty)
                        st += ` <tr><td style='border: 1px solid black;padding: 2px;text-align: left;'>${it.invName}</td>
                         <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.assQty}</td>
                         <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.unit}</td>
                         <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.qty}</td>
                         <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.price}</td>
                         <td style='border: 1px solid black;text-align: right;padding: 2px'>${it.amount}</td>
                         <td style='border: 1px solid black;padding: 2px;text-align: center;'>${it.remark}</td></tr>`
                    }
                    // 如有优惠金额 再加一行
                    if (disAmount !== 0) {
                        st += `<tr><td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td> <td   style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'> </td> 
                            <td style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>减扣：</td> 
                            <td style='border: 1px solid black;padding: 2px;text-align: right;'>${-disAmount}</td><td style='border: 1px solid black;padding: 2px;text-align: center;'></td></tr>`
                    }
                    // 如有收款金额 再加一行
                    if (rpAmount !== 0) {
                        st += `<tr><td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td><td   style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'> </td> 
                            <td  style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>已付：</td> 
                            <td style='border: 1px solid black;padding: 2px;text-align: right;'>${-rpAmount}</td><td style='border: 1px solid black;padding: 2px;text-align: center;'></td></tr>`
                    }
                    // 最后合计应收
                    if (arrears !== 0) {
                        st += `<tr>
                                    <td colspan='3' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'></td>
                                    <td   style='border: 1px solid black;padding: 2px;text-align: right; '>${allQty}</td>
                                    <td  style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>应收：</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${vInvoice.arrears}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    st += `</tbody> 
                                <tfoot >
                                    <tr>
                                        <td colspan='7' style='border: 1px solid black;padding: 5px 0'>金额：${arrears}大写：<span format='UpperMoney' tdata='${arrears}'>#</span></td> 
                                    </tr>`
                    if(descript) {
                        st += `<tr><td colspan='7' style=' padding-top: 2px;font-size: 12px;'>${descript}</td></tr>`
                    }
                    st += `<tr>
                                <td colspan='8' style='font-size: 14px'>
                                    <table style='width: 100%'>
                                        <tr>
                                            <td style='width: 120px;'>送货:</td>
                                            <td >制单:${userName}</td>
                                            <td >业务:${salesName}</td>
                                            <td style='width: 180px;'>未付款签字：</td>
                                        </tr>
                                    </table>
                                </td>
                           </tr>
                         </tfoot>`
                }
                if(transType === 150603) {
                    st += `
                            <tr>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>商品名称</td>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 75px;text-align: center;padding: 2px;'>辅助</td>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: center;padding: 2px;'>单位</td>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;;text-align: center;padding: 2px;'>数量</td>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 65px;text-align: center;padding: 2px;'>单价</td>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 70px;text-align: center;padding: 2px;'>金额</td>
                                    <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                                </tr>
                            </thead>
                        <tbody >
                    `
                    let list = await db.models['invoiceInfo'].findAll({
                        where: {
                            iid: vInvoice.id
                        }
                    })
                    let  tin = []
                    let tout = []
                    for (let i = 0; i < list.length; i++) {
                        let it = list[i]
                        it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                        it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                        if(it.trans === '换入') {
                            tin.push(it);
                        }
                        if(it.trans === '换出') {
                            tout.push(it);
                        }
                    }
                    for (let i = 0; i < tin.length; i++) {
                        let it = tin[i]
                        if (!it.invId) continue;
                        it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                        it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                        let invName = it.invName;
                        let unit = it.unit;
                        let quantity = -tool.xe.toNumber(it.qty)
                        let assisQty = it.assQty;
                        let deduction = it.deduction
                        let prices = it.price
                        let price = tool.minus(prices, deduction)
                        let sub = -tool.xe.toNumber(it.amount)
                        let beizhu = it.send + it.remark
                        st += "<tr ><td style='border: 1px solid black;padding: 2px;text-align: left;'>"
                        st += `<span  style='border-right: 1px solid grey;padding-right:5px;font-weight:800;'>换入</span><span>${invName}</span></td>`
                        st += `<td style='border: 1px solid black;padding: 2px;text-align: center;'>${assisQty}</td>`
                        st += `<td style='border: 1px solid black;padding: 2px;text-align: center;'>${unit}</td>`
                        st += `<td style='border: 1px solid black;text-align: center;padding: 2px'>${quantity}</td>`
                        st += `<td style='border: 1px solid black;text-align: right;padding: 2px'>${price}</td>`
                        st += `<td style='border: 1px solid black;text-align: right;padding: 2px'>${sub}</td>`
                        st += `<td style='border: 1px solid black;padding: 2px;text-align: center;'>${beizhu}</td></tr>`
                    }
                    for (let i = 0; i < tout.length; i++) {
                        let it = tin[i]
                        if (!it.invId) continue;
                        it.amount = tool.xe.toNumber(it.amount) === 0 ? '' : tool.xe.toFixed(it.amount, 2)
                        it.price = tool.xe.toNumber(it.price) === 0 ? '' : tool.xe.toFixed(it.price, 2)
                        let invName = it.invName;
                        let unit = it.unit;
                        let quantity = tool.xe.toNumber(it.qty)
                        let assisQty = it.assQty;
                        let deduction = it.deduction
                        let prices = it.price
                        let price = tool.minus(prices, deduction)
                        let sub = it.amount
                        let beizhu = it.send + it.remark
                        st += "<tr><td style='border: 1px solid black;padding: 2px;text-align: left;'>"
                        st += `     <span style='border-right: 1px solid grey;padding-right:5px;font-weight:800;'>换出</span><span>${invName}</span></td>`
                        st += `  <td style='border: 1px solid black;padding: 2px;text-align: center;'>${assisQty}</td>`
                        st += `   <td style='border: 1px solid black;padding: 2px;text-align: center;'>${unit}</td>`
                        st += `   <td style='border: 1px solid black;text-align: center;padding: 2px'>${quantity}</td>`
                        st += `   <td style='border: 1px solid black;text-align: right;padding: 2px'>${price}</td>`
                        st += `   <td style='border: 1px solid black;text-align: right;padding: 2px'>${sub}</td>`
                        st += `   <td style='border: 1px solid black;padding: 2px;text-align: center;'>${beizhu}</td></tr>`
                    }
                    // 如有优惠金额 再加一行
                    if (disAmount !== 0) {
                        st += `<tr>
                                    <td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>优惠金额：</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${-disAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    // 如有预收金额 再加一行
                    if (ysAmount !== 0) {
                        st += `<tr>
                                    <td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>预收抵扣：</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${-ysAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    // 如有收款金额 再加一行
                    if (rpAmount !== 0) {
                        st += `<tr>
                                    <td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>已收：-</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${rpAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                                </tr>`
                    }
                    // 最后合计应收
                    if (arrears !== 0) {
                        st += `<tr>
                                    <td colspan='5' style='border: 1px solid black;padding: 2px;text-align: right;font-size: 12px;'>应收：</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: right;'>${vInvoice.arrears}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }
                    st += `</tbody>
                                <tfoot >
                                    <tr>
                                        <td colspan='7' style='border: 1px solid black;padding: 5px 0'>金额：${arrears} 大写：<span format='UpperMoney' tdata='${arrears}'>#</span></td>
                                    </tr>`
                    if(descript) {
                        st += `<tr><td colspan='7' style='padding-top: 2px;'>${descript}</td></tr>`
                    }
                    st += `<tr>
                                <td colspan='8' style='font-size: 14px'>
                                    <table style='width: 100%'>
                                        <tr>
                                            <td style='width: 120px;'>送货:</td>
                                            <td >制单:${userName}</td>
                                            <td >业务:${salesName}</td>
                                            <td style='width: 180px;'>未付款签字：</td>
                                        </tr>
                                    </table>
                                </td>
                           </tr>
                         </tfoot>`
                }
            }
                break;
            case 153001:
            case 153101:
            case 153401:
            case 153402:
            case 153403:
            case 153404:
            case 153405:
            case 153406:
            case 153407: {
                st += `<tr><td colspan='7' style='font-size: 14px'><div >单位：${customerName}</div></td></tr>`
                if(transType === 153001) {
                    st += `<tr>
                 <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 160px;text-align: center;padding: 2px;'>收款账户</td>
                 <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 120px;text-align: center;padding: 2px;'>收款金额</td>
                 <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 120px;text-align: center;padding: 2px;'>收款优惠</td>
                 <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                 </tr>
                 </thead>
                 <tbody>`
                }
                if(transType === 153101) {
                    st += `<tr><td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 160px;text-align: center;padding: 2px;'>付款账户</td>
                     <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 120px;text-align: center;padding: 2px;'>付款金额</td>
                     <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 120px;text-align: center;padding: 2px;'>付款优惠</td>
                     <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                     </tr>
                     </thead>
                     <tbody>`
                }
                if(transType === 153001 || transType === 153101) {
                    let beizhu =  vInvoice.remark;
                    if (vInvoice.accId) {
                        st += `<tr>
                                    <td style='border: 1px solid black;padding: 2px;text-align: left;'>${vInvoice.accName}</td>
                                    <td style='border: 1px solid black;text-align: right;padding: 2px'>${vInvoice.accAmount}</td>
                                    <td style='border: 1px solid black;text-align: right;padding: 2px'>${vInvoice.disAmount}</td>
                                    <td style='border: 1px solid black;padding: 2px;text-align: center;'>${beizhu}</td>
                               </tr>`
                    }
                    if (vInvoice.accId1) {
                        st += `<tr>
                                     <td style='border: 1px solid black;padding: 2px;text-align: left;'>${vInvoice.accName1}</td>
                                     <td style='border: 1px solid black;text-align: right;padding: 2px'>${vInvoice.accAmount1}</td>
                                     <td style='border: 1px solid black;text-align: right;padding: 2px'></td>
                                     <td style='border: 1px solid black;padding: 2px;text-align: center;'></td>
                               </tr>`
                    }

                }
                if(transType === 153401 || transType === 153402 || transType === 153406 || transType === 153407) {
                    st += `<tr>
                                <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 160px;text-align: center;padding: 2px;'>账户</td>
                                <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 180px;text-align: center;padding: 2px;'>科目</td>
                                <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 120px;text-align: center;padding: 2px;'>金额</td>
                                <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                            </tr>
                          </thead>
                        <tbody>`
                    let list1 = await db.query(`select * from invoice_other where iid=${vInvoice.id}`)
                    for (let i = 0; i < list1.length; i++) {
                        let it = list1[i]
                        let payment = tool.xe.toNumber(it.amount)
                        if(payment !== 0) {
                            let beizhu =  it.remark
                            st += `<tr><td style='border: 1px solid black;padding: 2px;text-align: left;'>${it.accName}</td>
                                         <td style='border: 1px solid black;padding: 2px;text-align: left;'>${it.subjectName}</td>
                                         <td style='border: 1px solid black;text-align: right;padding: 2px'>${payment}</td>
                                        <td style='border: 1px solid black;padding: 2px;text-align: center;'>${beizhu}</td>
                                        </tr>`
                        }
                    }
                }
                if(transType === 153403) {
                    st += `<tr><td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black; text-align: center;padding: 2px;'>商品名称</td>
                       <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black; text-align: center;padding: 2px;'>单位</td>
                       <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black; text-align: center;padding: 2px;'>数量</td>
                       <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black; text-align: center;padding: 2px;'>单价</td>
                       <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black; text-align: center;padding: 2px;'>金额</td>
                       <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                       </tr>
                       </thead>
                       <tbody>`
                    let list1 = await db.query(`select * from invoice_info_ys where iid=${vInvoice.id}`)
                    for (let i = 0; i < list1.length; i++) {
                        let invoiceInfoYs = list1[i]
                        let price = invoiceInfoYs.price
                        let amounts = invoiceInfoYs.amount
                        let beizhu =  invoiceInfoYs.remark
                        let bd = i===list1.length-1 ? "border-bottom: 1px solid black;" : "";
                        st += `<tr><td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 260px;text-align: left;padding: 2px;${bd}'>${invoiceInfoYs.invName}</td>`
                        st += "  <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: center;padding: 2px;"
                        st += `${bd}'>${invoiceInfoYs.unit}</td>`
                        st += "  <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 40px;text-align: right;padding: 2px;"
                        st += `${bd}'>${invoiceInfoYs.qty}</td>`
                        st += "  <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 50px;text-align: right;padding: 2px;"
                        st += `${bd}'>${price}</td>`
                        st += "  <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 70;text-align: right;padding: 2px;"
                        st += `${bd}'>${amounts}</td>`
                        st += "  <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;"
                        st += `${bd}'>${beizhu}</td></tr></thead><tbody>`
                    }
                    st +=  " </tbody>" +
                        "<tfoot > <tr><td colspan='2' style='border: 1px solid black;text-align: left;padding:2px 2px 2px 0; ' > 总计： </td>"
                    st +=  "    <td style='border: 1px solid black;text-align: right;padding-right: 2px' tdata='SubSum' format='0'>###</td> " +
                        "<td style='border: 1px solid black;text-align: right;padding-right: 2px'   ></td>"
                    st +=  "    <td style='border: 1px solid black;text-align: right;padding-right: 2px' tdata='SubSum' format='0.00'>########</td>"
                    st +=  "    <td style='border: 1px solid black'></td></tr>"
                    st += `<tr><td > 制单人:${userName} </td> <td colspan='2' >经办人：${doName} </td><td > </td> </tr></tfoot>`
                }
                else {
                    st +=  ` </tbody>
                                 <tfoot > 
                                    <tr>
                                         <td  style='border: 1px solid black;text-align: left;padding:2px 2px 2px 0;width:200px' >合计：</td> 
                                         <td tindex='2' tdata='AllSum' format='0.00' style='border: 1px solid black;text-align: right;padding-right: 2px'  >########</td>
                                         <td tindex='3' tdata='AllSum' format='0.00' style='border: 1px solid black;text-align: right;padding-right: 2px'  >########</td>
                                         <td style='border: 1px solid black'></td></tr><tr><td > 制单人:${userName} </td> <td >经办人：${doName}  </td><td > </td>
                                    </tr>
                                 </tfoot>`
                }
            }
                break;
            case 160001: {
                st += `<tr>
                            <td colspan='7' style='font-size: 14px;height: 30px;'><div ></div></td>
                        </tr>
                        <tr>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 160px;text-align: center;padding: 2px;'>转出账户</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 160px;text-align: center;padding: 2px;'>转入账户</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;width: 120px;text-align: center;padding: 2px;'>转账金额</td>
                             <td style='border-left: 1px solid black;border-right: 1px solid black;border-top: 1px solid black;text-align: center;padding: 2px;'>备注</td>
                        </tr>
                      </thead>
                   <tbody>`
                let listTrans = await db.query(`select * from invoice_trans where iid=${vInvoice.id}`)
                for (let i = 0; i < listTrans.length; i++) {
                    let it = listTrans[i]
                    let remark = it.remark
                    st += `<tr><td style='border: 1px solid black;padding: 2px; text-align: left;'>${it.accName}</td>
                                 <td style='border: 1px solid black;padding: 2px;text-align: left;'>${it.accName1}</td>
                                 <td style='border: 1px solid black;padding: 2px;text-align: right;'>${it.amount}</td>
                                <td style='border: 1px solid black;padding: 2px;text-align: left;font-size: 12px;'>${remark}</td>
                           </tr>`
                }
                st += `</tbody><tfoot >
                                    <tr>
                                        <td colspan='2' style='border: 1px solid black;padding: 5px 0;font-size: 13px'></td> 
                                        <td style='border: 1px solid black;text-align: right;'>${vInvoice.amount}</td> 
                                        <td style='border: 1px solid black;padding: 5px 0;font-size: 13px;text-align: left;'></td></tr>
                                         <tr><td colspan='8' style='font-size: 14px'><table style='width: 100%'><tbody><tr><td >制单人:${userName}</td>
                                    </tr>
                      </tbody>
                    </table>
                    </td>
                </tr>
                </tfoot>`
            }
                break;
        }
        st += ' </table>'
        return  st
    }
    catch (e) {
        throw Error('数据取回失败')
    }
}
router.post('/bill/getPrint', async ctx => {
    let user  = ctx.user
    let uid = user.id
    let body  = ctx.request.body
    let tenantId = user.tenantId;
    // let uid = user.id;
    let roleId = user.roleId;
    let roleName = user.roleName;
    if (!roleName) {
        return ctx.err('还没有设置用户的角色');
    }
    if (!roleId) {
        return ctx.err('还没有设置用户的角色');
    }

    let isCard = body.isCard ? body.isCard : false;
    // let showPreview = body.direct ? "PRINT" : "PREVIEW";
    let ids = body.ids;
    if(ids.length === 0) return  ctx.err("请选择单据");
    if(ids.length > 50) return  ctx.err("最大支持 30 张单据批量打印");
    let op = await getOptionsByName(tenantId,  'system')
    let options = JSON.parse(op.value)
    let printHead = user.printHead ? user.printHead : options.printHead
    if(!printHead) return ctx.err('还没有设置打印抬头,请在设置->系统参数中设置')
    let descript = options.descript?options.descript:''

    if (!options.width) {
        return ctx.err("还未设置打印纸张宽度");
    }
    if (!options.height) {
        return ctx.err("还未设置打印纸张高度");
    }
    let  width = parseInt(options.width)
    let  height = parseInt(options.height)
    if(width === 0 ) return ctx.err("还未设置纸张宽度,请在 设置->系统参数 进行设置");
    if(height === 0 ) return ctx.err("还未设置纸张高度,请在 设置->系统参数 进行设置");
    if(!printHead)  return ctx.err("还未设置打印抬头,请在 设置->系统参数 进行设置");
    //
    let taskName = "出货单打印";

    let taskId = tool.uuid()
    let evals = []
    evals.push({str: `LODOP.PRINT_INIT('${taskName}')`})
    evals.push({str: "LODOP.SET_PREVIEW_WINDOW(1,2,1,900, 700)"})
    evals.push({str: `LODOP.SET_PRINT_PAGESIZE(0,${width},${height},'A4')`})
    let rets = {}
    // 取主票据
    if (!isCard) {
        let orders = await db.models['vInvoice'].findAll({
            where: {
                tenantId,
                id: {
                    [Op.in]: ids
                }
            }
        })

        // 打印记录
        let printRecords = []
        for (let i = 0; i < orders.length; i++) {
            let item = orders[i]
            let print = await printInfo(item, printHead,  descript);
            let printNo = tool.xe.toNumber(item.printNo) + 1;
            // 打印记录
            printRecords.push({
                tenantId: item.tenantId,
                iid: item.id,
                taskId: taskId,
                printBy: uid,
                printNo: printNo,
                stat: 0,
                printData: print
            })
            //
            evals.push({str: `LODOP.ADD_PRINT_BARCODE(2,550,90,90,'QRCode', '${item.transType}-${item.id}) + "')`});
            evals.push({str: '', data: print})
            if (orders.length > 1)  evals.push({str: 'LODOP.NewPageA()'});
        }
        // return ctx.err('还没有设置用户的角色');
        // evals.push({str: `LODOP.${showPreview}()`})
        //db.models['printRecord'].bulkCreate(printRecords)
        //
        rets.task_id = taskId
        rets.evals = evals
    }

    return ctx.suc('', rets);
})
//打印成功
router.post('/print/printSuc', async ctx => {
    let taskId = ctx.request.body.taskId;
    let t = tool.getTime()
    if (taskId) {
        try {
            await db.query(`update print_record set stat=1,printAt='${t}' where taskId='${taskId}'`, {type: QueryTypes.UPDATE});
            await db.query(`update invoice set printNo=isnull(printNo,0)+1 where id in (select iid from print_record where taskId='${taskId}')`, {type: QueryTypes.UPDATE});
        }
        catch (e) {

        }
    }
    return ctx.suc('');
})

router.post('/print/billPrintSuc', async ctx => {
    let tenantId = ctx.user.tenantId;
    let cargoId = ctx.request.body.cargoId;
    let cargo = await db.models['cargo'].findOne({
        where: {
            id: cargoId,
            tenantId
        }
    })
    cargoId.printNo = cargo.printNo ? cargo.printNo : 0;
    await cargo.save()
    return ctx.suc('');
})
module.exports = router;